<template>
    <a-drawer :title="formData.id ? '编辑测试地址维护' : '增加测试地址维护'" :width="600" :visible="visible" :destroy-on-close="true"
        :footer-style="{ textAlign: 'right' }" @close="onClose">
        <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
            <a-form-item label="Android：" name="testUrl">
                <a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card" class="avatar-uploader"
                    :customRequest="customRequest" :accept="fileImgType" :before-upload="beforeUpload"
                    @change="handleChange" @preview="handlePreview('1')">
                    <div v-if="fileList?.length == 0">
                        <plus-outlined></plus-outlined>
                        <div class="ant-upload-text">上传图片</div>
                    </div>
                </a-upload>
            </a-form-item>
            <a-form-item label="IOS：" name="testApp">
                <!-- <a-input v-model:value="formData.testApp" placeholder="请输入pc测试环境地址" allow-clear /> -->
                <a-upload v-model:file-list="fileList1" name="avatar" list-type="picture-card" class="avatar-uploader"
                    :customRequest="customRequest1" :accept="fileImgType" :before-upload="beforeUpload"
                    @change="handleChange1" @preview="handlePreview('2')">
                    <div v-if="fileList1?.length == 0">
                        <plus-outlined></plus-outlined>
                        <div class="ant-upload-text">上传图片</div>
                    </div>
                </a-upload>
            </a-form-item>
            <a-form-item label="pc测试环境地址：" name="pcTestUrl">
                <a-input v-model:value="formData.pcTestUrl" placeholder="请输入pc测试环境地址" allow-clear />
            </a-form-item>
        </a-form>
        <template #footer>
            <a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
            <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
        </template>
    </a-drawer>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="imaUrl" />
    </a-modal>
</template>

<script setup name="appInfoTestUrlForm">
import { cloneDeep } from 'lodash-es'
import { required } from '@/utils/formRules'
import appInfoTestUrlApi from '@/api/biz/appInfoTestUrlApi'
import fileApi from '@/api/dev/fileApi'
// 抽屉状态
const visible = ref(false)
const emit = defineEmits({ successful: null })
const fileUrl = import.meta.env.VITE_FILE_URL
const fileImgType = '.jpg,.png,.jpeg,'
const formRef = ref()
// 表单数据
const formData = ref({})
const submitLoading = ref(false)
const fileList = ref([])
const fileList1 = ref([])
const loading = ref(false)
const imageUrl = ref('')
const imageUrl1 = ref('')
const imaUrl = ref('')
let previewVisible = ref(false)
const fileHandle = (fileList) => {
    const file = fileList ? JSON.parse(fileList) : []
    file.map((item) => {
        if (item.url) {
            item.url = item.url.includes('http') ? item.url : `${fileUrl}/${item.url}`
        } else {
            // old
            item = `${fileUrl}/${item}`
        }
        return item
    })
    console.log(file)
    return file
}
// 打开抽屉
const onOpen = (record) => {
    visible.value = true
    if (record) {
        let recordData = cloneDeep(record)
        formData.value = Object.assign({}, recordData)
        fileList.value = fileHandle(formData.value.testUrl)
        fileList1.value = fileHandle(formData.value.testApp)
    } else {
        formData.value = {}
    }
}
// 关闭抽屉
const onClose = () => {
    formRef.value.resetFields()
    formData.value = {}
    visible.value = false
}
// 默认要校验的
const formRules = {
}
// 验证并提交数据
const onSubmit = () => {
    formRef.value
        .validate()
        .then(() => {
            submitLoading.value = true
            const formDataParam = cloneDeep(formData.value)
            appInfoTestUrlApi
                .appInfoTestUrlSubmitForm(formDataParam, !formDataParam.id)
                .then(() => {
                    onClose()
                    emit('successful')
                })
                .finally(() => {
                    submitLoading.value = false
                })
        })
}
// 自定义上传
const customRequest = (file) => {
    // 后端需要接受的参数是 formData数据，
    const form = new FormData()
    form.append('file', file.file)
    fileApi
        .uploadCosReturnUrlPub(form)
        .then((res) => {
            let arr = [{ name: file.file.name, url: res }]
            formData.value.testUrl = JSON.stringify(arr)
            file.onSuccess(res, file.file)
            file.status = 'done'
        })
        .catch((err) => {
            setTimeout(() => {
                file.onError()
            }, 1000)
        })
}
// 自定义上传
const customRequest1 = (file) => {
    // 后端需要接受的参数是 formData数据，
    const form = new FormData()
    form.append('file', file.file)
    fileApi
        .uploadCosReturnUrlPub(form)
        .then((res) => {
            let arr = [{ name: file.file.name, url: res }]
            formData.value.testApp = JSON.stringify(arr)
            file.onSuccess(res, file.file)
            file.status = 'done'
        })
        .catch((err) => {
            setTimeout(() => {
                file.onError()
            }, 1000)
        })
}
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
    const isLt2K = file.size / 1024 < 200
    return isJpgOrPng && isLt2K
}
const getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
}
const handleChange = (info) => {
    const { type, size } = info.file
    const isJpgOrPng = type === 'image/jpeg' || type === 'image/png' || type === 'image/jpg'
    const isLt2K = size / 1024 < 200
    if (!isJpgOrPng) {
        message.warning('图片类型不对')
        fileList.value = []
        return false
    }
    if (!isLt2K) {
        message.warning('图片大小不超过200K')
        fileList.value = []
        return false
    }
    if (info.file.status === 'uploading') {
        loading.value = true
        return
    }


    if (info.file.status === 'uploading') {
        loading.value = true
        return
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl.value = base64Url
            loading.value = false
        })
    }
    if (info.file.status === 'error') {
        loading.value = false
        fileList.value = []
        // message.error('上传失败')
    }
    if (info.file.status === 'removed') {
        formData.value.testUrl = ''
    }
}
const handleChange1 = (info) => {
    const { type, size } = info.file
    const isJpgOrPng = type === 'image/jpeg' || type === 'image/png' || type === 'image/jpg'
    const isLt2K = size / 1024 < 200
    if (!isJpgOrPng) {
        message.warning('图片类型不对')
        fileList1.value = []
        return false
    }
    if (!isLt2K) {
        message.warning('图片大小不超过200K')
        fileList1.value = []
        return false
    }
    if (info.file.status === 'uploading') {
        loading.value = true
        return
    }


    if (info.file.status === 'uploading') {
        loading.value = true
        return
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl1.value = base64Url
            loading.value = false
        })
    }
    if (info.file.status === 'error') {
        loading.value = false
        fileList1.value = []
        // message.error('上传失败')
    }
    if (info.file.status === 'removed') {
        formData.value.testApp = ''
    }
}
const handlePreview = (num) => {
    if (num === '1') {
        imaUrl.value = imageUrl.value || fileList.value[0].url
    } else {
        imaUrl.value = imageUrl1.value || fileList1.value[0].url
    }
    previewVisible.value = true
}
const handleCancel = () => {
    previewVisible.value = false
}
// 抛出函数
defineExpose({
    onOpen
})
</script>
